using Unity.Burst;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

partial struct PlayerSystem : ISystem
{
    [BurstCompile]
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<GamePreComponent>();
    }

    [BurstCompile]
    public void OnUpdate(ref SystemState state)
    {
        var gamePre=SystemAPI.GetSingleton<GamePreComponent>();
        var playerEn=SystemAPI.GetSingletonEntity<PlayerControlComponent>();
        RefRO<LocalTransform> playerTrans=SystemAPI.GetComponentRO<LocalTransform>(playerEn);
        foreach(var (atri,nBulletAbt,en) in SystemAPI.Query<RefRO<CharacterAttributeComponent>,RefRW<NormalBulletAbilityComponent>>().WithEntityAccess()){
            nBulletAbt.ValueRW.timer-=SystemAPI.Time.DeltaTime;
            if(nBulletAbt.ValueRO.timer<=0){
                if(state.EntityManager.HasComponent<PlayerControlComponent>(en))
                {
                    RefRO<LocalTransform> nearestenmy=default;
                    float maxDis=999999;
                    foreach (var trans in SystemAPI.Query<RefRO<LocalTransform>>().WithAny<EnemyComponent>())
                    {
                        float dis=math.distance(trans.ValueRO.Position,playerTrans.ValueRO.Position);
                        if(dis<maxDis){
                            nearestenmy=trans;
                            maxDis=dis;
                        }
                    }
                    if(maxDis<=nBulletAbt.ValueRO.range){
                        var bullet=state.EntityManager.Instantiate(gamePre.bulletPre);
                        var bulletTrans=SystemAPI.GetComponentRW<LocalTransform>(bullet);
                        bulletTrans.ValueRW.Position=playerTrans.ValueRO.Position;
                        var bulletData=SystemAPI.GetComponentRW<BulletDataComponet>(bullet);
                        bulletData.ValueRW.demage=atri.ValueRO.demage*nBulletAbt.ValueRO.demagePercent;
                        bulletData.ValueRW.isPlayer=true;
                        bulletData.ValueRW.lifeTime=2f;
                        bulletData.ValueRW.lifeTimer=bulletData.ValueRO.lifeTime;
                        var bulletMove=SystemAPI.GetComponentRW<MoveComponent>(bullet);
                        bulletMove.ValueRW.dir=math.normalize(nearestenmy.ValueRO.Position-playerTrans.ValueRO.Position);
                        bulletMove.ValueRW.speed=10f;
                        nBulletAbt.ValueRW.timer=nBulletAbt.ValueRO.cd;
                    }
                }

                

            }
        }
    }

    [BurstCompile]
    public void OnDestroy(ref SystemState state)
    {
        
    }
}
